package com.ifonly.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-29 20:17
 * @since JDK 1.6
 */
public class IfonlySecurity {

    // ----------------------------------------------------------- login

    /**
     * 登录操作
     *
     * @param account 账号
     * @param password 密码
     */
    public static void login(String account, String password) {
        login(account, password, false);
    }

    /**
     * 登录操作
     *
     * @param account 账号
     * @param password 密码
     * @param remember 是否"记住我"
     */
    public static void login(String account, String password, boolean remember) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        token.setRememberMe(remember);

        try {
            subject.login(token);
        } catch (LockedAccountException e) {
            throw new RuntimeException("锁定的帐号", e);
        } catch (DisabledAccountException e) {
            throw new RuntimeException("禁用的帐号", e);
        } catch (UnknownAccountException e) {
            throw new RuntimeException("错误的帐号", e);
        } catch (ExcessiveAttemptsException e) {
            throw new RuntimeException("登录失败次数过多");
        } catch (IncorrectCredentialsException e) {
            throw new RuntimeException("错误的凭证", e);
        } catch (ExpiredCredentialsException e) {
            throw new RuntimeException("过期的凭证", e);
        } catch (Exception e) {
            throw new RuntimeException("账号密码错误", e);
        }
    }

    // ----------------------------------------------------------- logout

    /**
     * 推出登录
     */
    public static void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

    /**
     * 获取权限实体
     *
     * @param <ID> id类型
     * @param <E> 关联信息
     * @return 登录信息
     */
    @SuppressWarnings("unchecked")
    public static <ID, E> SecurityEntry<ID, E> getSecurityEntry() {
        Subject subject = SecurityUtils.getSubject();
        Object o = subject.getPrincipal();
        return (SecurityEntry<ID, E>) o;
    }

}
